
import Rect from './ts/rect';
import Snake from './ts/snake';

// 定义全局食物对象
let foodRect: Rect;


let snake = new Snake(".container");

createFood();

let timer = null;
// 利用定时器让蛇运动起来
timer = setInterval(() => {
    snake.move();

    let rect = new Rect(snake.leftNum, snake.topNum);
    snake.body.splice(1, 0, rect);
    // 检测蛇头是否和食物碰撞了；
    if (Math.abs(snake.head.getleft() - foodRect.getleft()) < 50 && Math.abs(snake.head.getTop() - foodRect.getTop()) < 50) {
        console.log("吃到食物了");
        // 吃到食物，在生成一个食物
        snake.container.removeChild(foodRect.RectEle);
        createFood();
    } else {
        let lastEle = snake.body.pop().RectEle;
        snake.container.removeChild(lastEle);
    }
    snake.createBody();
    snake.borderLimit(timer);
}, 500)









document.onkeydown = function (e) {
    let code = e.key;
    console.log(code);
    switch (code) {
        case 'ArrowLeft':
            snake.dir = "left";
            break;
        case 'ArrowUp':
            snake.dir = "up";
            break;
        case 'ArrowRight':
            snake.dir = "right";
            break;
        case 'ArrowDown':
            snake.dir = "down";
            break;
        default:
            console.log("其他按键");
            break;
    }
}

function randomNum(min:number, max:number) {
    return parseInt(Math.random() * (max - min + 1)+"") + min
}





function createFood() {
    let leftNum = randomNum(0, 11);
    let topNum = randomNum(0, 11);
    // 判断食物随机不能在蛇身体上；
    // 判断不能在身体上
    let judge = false;
    snake.body.forEach(item => {
        let bodyLeft = item.getleft();
        let bodyTop = item.getTop();
        if (leftNum * 50 == bodyLeft && topNum * 50 == bodyTop) {
            judge = true;
        }
    })
    console.log(judge);

    if (judge) {
        createFood();
    } else {
        let rect = new Rect(50 * leftNum, 50 * topNum, "yellow");
        foodRect = rect;
        rect.createRect(document.querySelector(".container"));
    }

}